package stardust.product.platform.webc.spi.servlet.jsp.tag;


import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import stardust.product.platform.webc.WebcContext;
import stardust.product.platform.webc.spi.servlet.ServletWebcRequestHandler;
import stardust.product.platform.webc.support.WebcContextUtils;


public class InvokeTag extends AbstractDynamicAttributesTag
{

  private static final long serialVersionUID = 1L;

  public int doStartTag() throws JspException
  {
    return AbstractDynamicAttributesTag.EVAL_PAGE;
  }

  public int doAfterBody() throws JspException
  {
    return AbstractDynamicAttributesTag.EVAL_PAGE;
  }

  public int doEndTag() throws JspException
  {
    HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) super.pageContext.getResponse();
    ServletWebcRequestHandler webcProcessor;

    if (super.attribute != null)
    {
      Iterator<String> pre = super.attribute.keySet().iterator();
      String preKey;
      Map<String, String> preValue;

      WebcContext ctx;

      while (pre.hasNext())
      {
        preKey = pre.next();
        preValue = super.attribute.get(preKey);

        if (preKey == null)
        {
          ctx = WebcContextUtils.getDefaultContext();
        }
        else
        {
          ctx = WebcContextUtils.getContext(preKey);
        }
        
        webcProcessor = new ServletWebcRequestHandler(ctx, request, response);

        Iterator<String> attr = preValue.keySet().iterator();
        String attrKey;
        String attrValue;

        while (attr.hasNext())
        {
          attrKey = attr.next();
          attrValue = preValue.get(attrKey);

          try
          {
            request.setAttribute(attrKey, ctx.invokeWithNoRender(attrValue, webcProcessor));
          }
          catch (Throwable e)
          {
            throw new JspException(e);
          }
        }
      }
    }
    
    super.attribute.clear();

    return AbstractDynamicAttributesTag.EVAL_PAGE;
  }

}
